/**
 * 所有单位全选和取消全选功能
 */
function checkAll(obj) {
    const table = $("#companyTable");
    setCheck(obj, table);
}

/**
 * 设置行中复选框全选和取消全选
 * @param obj
 */
function checkRow(obj) {
    const tr = $(obj).closest('tr');
    setCheck(obj, tr);
}

/**
 * 点击每个具体公司种类时，反选对应行前种类复选框
 * @param obj 协执单位复选框
 */
function checkKind(obj) {
    const tr = $(obj).closest('tr');
    const kindTd = $(tr).children("td:first-child");
    //setCheck(obj, kindTd);
    let spanBox = kindTd.find('.checkBox');
    let checkBox = kindTd.find('.inputCheck');
    if($(obj).is(":checked")) {
        spanBox.addClass('checkbox_checked');
        checkBox.attr('checked', 'checked');
    }
}

/**
 * 根据点击的复选框，设置区域内复选框全选和取消
 * @param obj 点击的复选框
 * @param parentObj 需要设置的复选框所在父区域节点
 */
function setCheck(obj, parentObj) {
    let spanBox = parentObj.find('.checkBox');
    let checkBox = parentObj.find('.inputCheck');
    if ($(obj).is(":checked")) {
        spanBox.addClass('checkbox_checked');
        checkBox.attr('checked', 'checked');
    } else {
        spanBox.removeClass('checkbox_checked');
        checkBox.removeAttr('checked');
    }
}

/**
 * 删除勾选的查询对象表
 */
function removeFrame() {

    let div = $("#divQueryObj");
    let iframe = div.find('iframe');

    //计算复选框勾选个数
    let checkedBoxNum = iframe.contents().find(".inputCheck:checked").size();

    //未勾选、全勾选时不删除
    if (checkedBoxNum === 0) {
        layer.msg("未勾选删除行");
    } else if (checkedBoxNum < iframe.size()) {
        layer.confirm("确定删除所有选中行？", {
            btn: ['确定', '取消'],
            title: "删除"
        }, function (index) {
            iframe.each(function () {
                let checkedBox = $(this).contents().find(".inputCheck");
                if (checkedBox.is(":checked")) {
                    $(this).remove();
                }
            });

            //关闭提示弹窗
            layer.close(index);
        });
    } else {
        layer.msg("删除失败，至少保留一张查询对象表单");
    }
}

/**
 * 下载文件
 * @param fileName 实际文件名
 * @param filePath 路径
 */
function downloadFile(fileName, filePath) {
    if (fileName != null && fileName !== "") {
        var params = {
            "filePath": filePath,
            "fileName": fileName,
        };
        var url = CONTEXT_PATH + "/ck/downloadFile";
        var temp_form = createForm(url, params);
        temp_form.submit();
    } else {
        layer.msg("系统错误，文件不存在");
    }
}

/**
 * 创建表单，通过url，params实现表单提交
 * @param url 请求url
 * @param params 表单参数
 * @returns {HTMLFormElement}
 */
function createForm(url, params) {
    var temp_form = document.createElement("form");
    temp_form.action = url;
    temp_form.target = "_self";
    temp_form.method = "post";
    temp_form.style.display = "none";
    for(var param in params) {
        var opt = document.createElement("textarea");
        opt.name = param;
        opt.value = params[param];
        temp_form.appendChild(opt);
    }
    document.body.appendChild(temp_form);
    return temp_form;
}

/**
 * 保存按钮
 */
function saveTable(zt) {

    //校验必填项是否为空
    let required = false;

    let div = $("#divQueryObj");
    let iframe = div.find('iframe');
    let require = iframe.contents().find(".require");

    //未填写的必填项，设置背景高亮
    require.each(function () {
        if (!$.trim($(this).val())) {
            required = true;
            $(this).closest("td[class='tdCont']").css("background-color", "yellow");
        } else {
            $(this).closest("td[class='tdCont']").css("background-color", "white");
        }
    })

    //取消保存
    if (required) {
        layer.msg("存在必填项未填写，请填写后保存", {time: 1000});
        return;
    }

    //协执单位复选框至少勾选一项
    let checkedNum = $(".companyEach:checked").size();
    if (checkedNum <= 0) {
        layer.msg("至少勾选一项协执单位！", {time: 1000});
        return;
    }

    var type = getUrlParam().type;
    let url = CONTEXT_PATH + "ck/saveCkdxes";
    if (type === 'add') {
        url += "?type=add";
    } else if (type === 'edit') {
        url += '?type=edit';
    }

    // 获取页面中的协执说明和登记批次
    let xzsm = $.trim($("#xzsm").val());
    let djpc = $.trim($("#djpc").val());

    //遍历iframe保存查询对象列表
    let queryObjArr = [];
    iframe.each(function () {

        let content = $(this).contents();

        //获取iframe中的表单值
        let ah = $.trim(content.find("input[name='ah']").val());
        let cbr = $.trim(content.find("input[name='cbr']").val());
        let sjy = $.trim(content.find("input[name='sjy']").val());
        let mc = $.trim(content.find("input[name='mc']").val());
        let ssdw = $.trim(content.find("select[name='ssdw']").val());
        let zjlx = $.trim(content.find("select[name='zjlx']").val());
        let zjhm = $.trim(content.find("input[name='zjhm']").val());
        let gj = $.trim(content.find("select[name='gj']").val());
        let hjszd = $.trim(content.find("input[name='hjszd']").val());
        let cklsh = $.trim(content.find("#cklsh").val());

        //获取勾选的协执单位
        let map = new Object();
        $(".companyKind:checked").each(function () {
            let kindChecked = $(this).val();

            //存储勾选的协执单位
            let eachChecked = [];
            let companyEach = $(this).closest("tr").find(".companyEach:checked");

            companyEach.each(function (index, value) {
                eachChecked.push($(value).val());
            });

            //勾选了协执单位类别，且勾选了协执单位，存入map<String, Array()>
            if (eachChecked.length > 0) {
                map[kindChecked] = eachChecked;
            }
        });

        let queryObj = {
            'ah': ah,
            'cbr': cbr,
            'sjy': sjy,
            'mc': mc,
            'ssdw': ssdw,
            'zjlx': zjlx,
            'zjhm': zjhm,
            'gj': gj,
            'hjszd': hjszd,
            'zt': zt,
            'xzsm': xzsm,
            'cklsh': cklsh,
            'djpc': djpc,
            'xzdw': map,
            'jz': wjList,
            'deleteSavedFiles': deleteSavedFileList
        };
        queryObjArr.push(queryObj);
    });

    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(queryObjArr),
        success: function (result) {

            if (result.code === 200) {

                //根据上次点击查询的条件进行加载
                window.parent.loadData(window.parent.status, window.parent.caseNum, window.parent.executor, window.parent.idNum);
                goBack();
                parent.layer.msg("保存成功", {time: 1000});
            } else {
                layer.msg("保存失败！", {time: 1000});
            }
        },
        error: function () {
            layer.alert("请求异常！");
        }
    });
}

function sendFile() {
    var fileDiv = $(".fileDiv");
    if(fileDiv.length <= 0) {
        layer.msg("请上传文书");
    } else {
        saveTable(60);
    }
}

/**
 * 返回 关闭页面
 */
function goBack() {

    //先得到当前iframe层的索引,关闭layer
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}


/**
 * 删除临时文件
 */
function delFile() {

    let deletePathArr = [];
    let wjArr = wjList;

    let allFileDiv = $("#allFile");
    const checkBox = allFileDiv.find(".inputCheck");
    const newFileCheck = allFileDiv.find(".isNewFile");
    const savedFileCheck = allFileDiv.find(".isSavedFile");

    //新增文件
    newFileCheck.each(function () {
        if($(this).is(":checked")) {
            let path = $(this).parent().find(".wholePath").val();
            deletePathArr.push(path);
            wjArr[$(this).val()] = {};
        }
    });

    //遍历已入库文件
    savedFileCheck.each(function () {
        if($(this).is(":checked")) {
            wjArr[$(this).val()] = {};
            deleteSavedFileList.push($(this).parent().find('.wholePath').val());
        }
    });

    if (checkBox.length <= 0) {
        layer.msg("请勾选要删除的文件");
    } else {
        layer.confirm("确定删除选中文件", {
            btn: ['确定', '取消'],
            title: "删除"
        }, function () {
            $.ajax({
                type: "post",
                url: CONTEXT_PATH + "ck/deleteTempFile",
                contentType: 'application/json;charset=utf-8',
                data: JSON.stringify(deletePathArr),
                success: function (result) {

                    // 删除成功
                    if (result.code === 200) {
                        checkBox.each(function () {
                            if ($(this).is(":checked")) {
                                $(this).parent('.fileDiv').remove();
                            }
                        });
                        wjList = wjArr;
                        layer.msg("删除成功！", {time: 1000});
                    } else {
                        layer.msg("删除失败！", {time: 1000});
                    }
                },
                error: function (r, s, e) {
                    layer.alert("请求异常！");
                }
            });
        });
    }
}

/**
 * 新增页面初始显示一个iframe，查看、编辑页面根据同一批次查询对象个数添加
 * @param type 页面类型
 * @param ckxzes 查控对象
 */
function loadFrame(type, ckxzes) {

    //将所有同一批次的查询对象添加到表单
    if (type === 'edit' || type === 'view') {
        if (ckxzes != null) {

            //设置协执说明和登记批次
            $("#xzsm").val(ckxzes[0].xzsm);
            $("#djpc").val(ckxzes[0].djpc);

            //初始化表单
            for (let i = 0; i < ckxzes.length; i++) {
                addFrame(i);
            }
        }

        if(wjList !== null) {
            for(var i = 0; i < wjList.length; i++) {
                var wj = wjList[i];
                var path = wj.path.replace(/\\/g, '\\\\');
                var wholePath = path + "\\\\" + wj.wjmc;

                //表中放入文件图标和名称
                var imgSrc = "";
                if (wj.wjlx === 'pdf') {
                    imgSrc = CONTEXT_PATH + "/static/images/pdf.PNG";
                } else {
                    imgSrc = CONTEXT_PATH + "/static/images/doc.PNG";
                }
                var fileHtml = "<div class='fileDiv'>" +
                    "<input class='inputCheck isSavedFile' type='checkbox' value='" + fileListIndex + "'/>" +
                    "<input type='hidden' class='wholePath' value='" + wholePath + "' />" +
                    "<img src=\"" + imgSrc + "\" alt='文件' title=\"点击下载查看\" onclick=\"downloadFile('" + wj.wjmc + "','" + path + "')\"/>" +
                    wj.wjmc +
                    "</div>";

                $("#allFile").append(fileHtml);
                checkboxInit($(".fileDiv").find(".inputCheck"));
                fileListIndex = i + 1;
            }
        }
    } else {

        // djpc使用新生成32位uuid
        $("#djpc").val(getUuid(32, 16));

        //新增一个iframe
        addFrame(-1);
    }

}

/**
 * 新增查询对象表iframe
 * @param no 为-1表示后来新增的，>=0表示页面初始加载显示的
 */
function addFrame(no) {
    let html = "<iframe data-id='iframeTable' src='frameTable?no=" + no + "' frameBorder='0' scrolling='no' style='width: 100%; height: 160px'></iframe>"
    $("#divQueryObj").append(html);
}

/**
 * 设置协执单位选中
 */
function setChecked(xzdw) {

    $(".companyEach").each(function () {
        for(var i = 0; i < xzdw.length; i++) {
            if(xzdw[i] === $(this).val()) {
                setCheckVal($(this), true);
                checkKind($(this));
            }
        }
    });
}

/**
 * 设置页面按钮禁用
 */
function setDisabled() {
    checkDisable(".inputCheck", 'disabled');
    $("#xzsm").attr("readonly", true);
    $(".tdh_btn").addClass("tdh_btn_disable");
}
